package com.Mobile.Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import transformFactory.DateJsonValueProcessor;

import com.Entity.Orders;
import com.Entity.Userhealthdata;
import com.Entity.Users;
import com.Service.OrderService;
import com.Service.UserHealthDataService;
import com.Service.UsersService;

public class MobileSaveOrderAction implements ServletResponseAware {
	 //填写医嘱
	private HttpServletResponse response;//response闁诲海鏁搁、濠囨寘?
	private int flag=0;
	@Autowired
	private OrderService orderservice;
	@Autowired
	private UsersService usersservice;
	@Autowired
	private UserHealthDataService userhealthdataservice;
	private List<Orders> orderlist=new ArrayList<Orders>();
	private Userhealthdata userhealthdata=new Userhealthdata();
	private Orders order=new Orders();
	private List<Userhealthdata> userhealthdatalist=new ArrayList<Userhealthdata>();
	private List<Map<String, Object>> userlist=new ArrayList<Map<String, Object>>();//
	private Users user=new Users();
	
	public void saveorder() throws ServletException,IOException{
		// TODO Auto-generated method stub
		
		
		String dataid=ServletActionContext.getRequest().getParameter("DataID");
		String orders=ServletActionContext.getRequest().getParameter("Orders");
		String doctorid=ServletActionContext.getRequest().getParameter("DoctorID");
		
		orders = new String(orders.getBytes("ISO-8859-1"), "UTF-8");
						
		dataid = java.net.URLDecoder.decode(dataid,"UTF-8");
		orders = java.net.URLDecoder.decode(orders,"UTF-8");
		doctorid = java.net.URLDecoder.decode(doctorid,"UTF-8");				
		
		JSONObject returnjson=new JSONObject();
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(dataid);
			userhealthdata=this.userhealthdataservice.getById(id);
			if(userhealthdata!=null){
				flag=1;
				int doctorid1=Integer.parseInt(doctorid);
				userhealthdata.setDoctorId(doctorid1);
				userhealthdata.setOrderState((short) 1);
				
				orderlist=this.orderservice.findByDataId(id);
				
				if(!orderlist.isEmpty()){
					order=orderlist.get(0);
					order.setOrderContent(orders);
					order.setOrderUploadTime(new Date());
					this.orderservice.update(order);
					
				}else{
				int motherid=userhealthdata.getUserId();
				order.setUserId(doctorid1);
				order.setMotherId(motherid);
				order.setDataId(id);
				order.setOrderContent(orders);
				order.setOrderUploadTime(new Date());
				this.orderservice.save(order);
				
				}
				returnjson.put("flag", flag);
			}else{
				flag=0;
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//移交中心医院
	public void transfertoconter() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String dataid=ServletActionContext.getRequest().getParameter("DataID");		
		dataid = java.net.URLDecoder.decode(dataid,"UTF-8");
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(dataid);
			userhealthdata=this.userhealthdataservice.getById(id);
			System.out.println(userhealthdata);
			if(userhealthdata!=null){
				flag=1;
				userhealthdata.setTransferState((short)1);
				this.userhealthdataservice.save(userhealthdata);
				returnjson.put("flag", flag);
			}else{
				flag=0;
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//社区医生查看孕妇历史健康数据列表、孕妇端查看历史健康数据列表
	public void orderlist() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String userid=ServletActionContext.getRequest().getParameter("UserID");	//孕妇id	
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(userid);
			userhealthdatalist=this.userhealthdataservice.findByUserId(id);
			
			System.out.println(userhealthdatalist);
			if(userhealthdatalist!=null){
				flag=1;
				
				JsonConfig jsonConfig = new JsonConfig();
				  jsonConfig.registerJsonValueProcessor(Date.class,
				  new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
				  JSONArray jsonArray = JSONArray.fromObject(userhealthdatalist, jsonConfig);
				  returnjson.put("flag", flag);  
				returnjson.put("userhealthdata", jsonArray);
				
			}else{
				flag=0;
				
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//根据日期查看数据
	public void DataList() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String userid=ServletActionContext.getRequest().getParameter("UserID");	//孕妇id	
		String datauploadtime=ServletActionContext.getRequest().getParameter("DataUploadTime");		
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
		datauploadtime = java.net.URLDecoder.decode(datauploadtime,"UTF-8");
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(userid);
			userhealthdatalist=this.userhealthdataservice.findByUserId(id);			
			System.out.println(userhealthdatalist);
			if(userhealthdatalist!=null){
				flag=1;			
				 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				 Date tdate =df.parse(datauploadtime);				
				    Map<String, Object> params = new HashMap<String, Object>();
					params.put("id", id);
					params.put("tdate", tdate);
					System.out.println(params);
					String sql="select * from userhealthdata where UserID =:id and DataUploadTime=:tdate";
					userhealthdatalist=this.userhealthdataservice.findBySql(sql, params);
					System.out.println(userhealthdatalist);
					JsonConfig jsonConfig = new JsonConfig();
					jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
					JSONArray jsonArray = JSONArray.fromObject(userhealthdatalist,jsonConfig);
					returnjson.put("flag", flag);  
				    returnjson.put("userhealthdata", jsonArray);
				
			}else{
				flag=0;
				
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//社区查看孕妇列表
	public void CommunityUserList() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String communityid=ServletActionContext.getRequest().getParameter("CommunityID");	//孕妇id		
		communityid = java.net.URLDecoder.decode(communityid,"UTF-8");		
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(communityid);
			if(userhealthdatalist!=null){
				flag=1;					
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("id", id);
				System.out.println(params);
				String sql="select UserID,UserName,NickName from users where CommunityID =:id ";
				userlist=this.usersservice.findBySql(sql, params);			
				returnjson.put("flag", flag);  
			    returnjson.put("userhealthdata", userlist);
			
			}else{
				flag=0;
				
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//社区医生填写医嘱前查看孕妇健康数据（只查看未填写医嘱的数据）
	public void CommonDataList() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String communityid=ServletActionContext.getRequest().getParameter("CommunityID");	//孕妇id		
		communityid = java.net.URLDecoder.decode(communityid,"UTF-8");		
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(communityid);
			if(userhealthdatalist!=null){
				flag=1;					
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("id", id);
				System.out.println(params);
				String sql="select UserID from users where CommunityID =:id ";
				userlist=this.usersservice.findBySql(sql, params);
				System.out.println(userlist);
					
				
				
				List list=new ArrayList();
				for(Map<String, Object> entry:userlist){    
					/*Iterator iterator = hm.keySet().iterator();*/
					
					Map<String, Object> params1 = new HashMap<String, Object>();
					long userid = Long.parseLong(entry.get("UserID").toString()) ;
				    params1.put("id", userid);
				    params1.put("state",0);
					System.out.println(params1);
					
					String sql1="select * from userhealthdata where UserID =:id and OrderState=:state";
					userhealthdatalist=this.userhealthdataservice.findBySql(sql1, params1);
					list.add(userhealthdatalist);
				}
				JsonConfig jsonConfig = new JsonConfig();
				jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
				JSONArray jsonArray = JSONArray.fromObject(list,jsonConfig);
				
				returnjson.put("flag", flag);  
			    returnjson.put("userhealthdata", jsonArray);
			
			}else{
				flag=0;
				
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//孕妇分页查看历史健康数据
	public void HistoryData() throws Exception{
		String userid= ServletActionContext.getRequest().getParameter("UserID");
		String currpage =  ServletActionContext.getRequest().getParameter("CurrPage");
		String pagesize =  ServletActionContext.getRequest().getParameter("PageSize");
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
		currpage = java.net.URLDecoder.decode(currpage,"UTF-8");
		pagesize = java.net.URLDecoder.decode(pagesize,"UTF-8");
	    HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		JSONObject returnjson=new JSONObject();
		
		int intuserid=Integer.parseInt(userid);
		int intcurrpage = Integer.parseInt(currpage);
		int intpagesize = Integer.parseInt(pagesize);
		
		if(userid!=null&&!userid.equals("")){		
			userhealthdatalist=this.userhealthdataservice.getHealthdataListByUserId(intuserid, intcurrpage, intpagesize);
			System.out.println(userhealthdatalist);
            if(userhealthdatalist!=null){
            	
            	JSONArray jsonbean=JSONArray.fromObject(userhealthdatalist);
				flag=1;
				returnjson.put("flag",flag);
		
				returnjson.put("info", jsonbean);				
			}
			else{
				returnjson.put("flag", flag);
			}
		}
		else{
			returnjson.put("flag", flag);
		}
		out.println(returnjson.toString());
		out.flush();
		out.close();
	}
	//孕妇端查看某条数据的具体信息
	public void detaildata() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String dataid=ServletActionContext.getRequest().getParameter("DataID");	//孕妇id	
		dataid = java.net.URLDecoder.decode(dataid,"UTF-8");
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(dataid);
			if(userhealthdata!=null){
				flag=1;
			userhealthdata=this.userhealthdataservice.getById(id);	
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
			JSONArray jsonArray = JSONArray.fromObject(userhealthdata,jsonConfig);
			System.out.println(userhealthdata);							
	        returnjson.put("flag", flag);  
			returnjson.put("userhealthdata", jsonArray);
				
			}else{
				flag=0;			
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//社区端查看某孕妇某条数据并设为已读
	public void OrderDetailData() throws ServletException,IOException{
		// TODO Auto-generated method stub		
		String dataid=ServletActionContext.getRequest().getParameter("DataID");	//孕妇id	
		dataid = java.net.URLDecoder.decode(dataid,"UTF-8");
		JSONObject returnjson=new JSONObject();		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(dataid);
			if(userhealthdata!=null){
				flag=1;
			userhealthdata=this.userhealthdataservice.getById(id);
			userhealthdata.setDataReadState((short) 1);
			this.userhealthdataservice.save(userhealthdata);
			System.out.println(userhealthdata);	
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
			JSONArray jsonArray = JSONArray.fromObject(userhealthdata,jsonConfig);
	        returnjson.put("flag", flag);  
			returnjson.put("userhealthdata", jsonArray);
				
			}else{
				flag=0;			
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//孕妇端查看医嘱（只查看已填写医嘱的数据）
	public void PregnantOrderData() throws ServletException,IOException{	
			String userid= ServletActionContext.getRequest().getParameter("UserID");//孕妇id
			String currpage =  ServletActionContext.getRequest().getParameter("CurrPage");
			String pagesize =  ServletActionContext.getRequest().getParameter("PageSize");
			userid = java.net.URLDecoder.decode(userid,"UTF-8");
			currpage = java.net.URLDecoder.decode(currpage,"UTF-8");
			pagesize = java.net.URLDecoder.decode(pagesize,"UTF-8");
		    HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = response.getWriter();			
			JSONObject returnjson=new JSONObject();			
			int intuserid=Integer.parseInt(userid);
			int intcurrpage = Integer.parseInt(currpage);
			int intpagesize = Integer.parseInt(pagesize);			
			if(userid!=null&&!userid.equals("")){		
				orderlist=this.orderservice.getOrdersListByMotherId(intuserid, intcurrpage, intpagesize);
				System.out.println(orderlist);				
	            if(orderlist!=null){	            	
	            	JsonConfig jsonConfig = new JsonConfig();
	    			jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
	    			JSONArray jsonArray = JSONArray.fromObject(orderlist,jsonConfig);
					flag=1;
					returnjson.put("flag",flag);			
					returnjson.put("info", jsonArray);				
				}
				else{
					returnjson.put("flag", flag);
				}
			}
			else{
				returnjson.put("flag", flag);
			}
			out.println(returnjson.toString());
			out.flush();
			out.close();
		}
	//查看血压趋势图（包括收缩压和舒张压）
	public void BloodPressure() throws ServletException,IOException{
		// TODO Auto-generated method stub
		String userid=ServletActionContext.getRequest().getParameter("UserID");
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
        JSONObject returnjson=new JSONObject();	
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(userid);
			if(userid!=null&&!userid.equals("")){
				flag=1;
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("id", id);
				System.out.println(params);
				String sql="select DiastolicPressure,SystolicPressure from userhealthdata where UserID =:id ";
				userhealthdatalist=this.userhealthdataservice.findBySql(sql, params);					
				System.out.println(userhealthdatalist);
				returnjson.put("flag", flag);
				returnjson.put("BloodPressure", userhealthdatalist);
			}else{
				flag=0;			
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//查看血糖趋势图
	public void BloodSugar() throws ServletException,IOException{
		// TODO Auto-generated method stub
		String userid=ServletActionContext.getRequest().getParameter("UserID");
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
        JSONObject returnjson=new JSONObject();	
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(userid);
			if(userid!=null&&!userid.equals("")){
				flag=1;
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("id", id);
				System.out.println(params);
				String sql="select BloodSugar from userhealthdata where UserID =:id ";
				userhealthdatalist=this.userhealthdataservice.findBySql(sql, params);					
				System.out.println(userhealthdatalist);
				returnjson.put("flag", flag);
				returnjson.put("BloodSugar", userhealthdatalist);
			}else{
				flag=0;			
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//查看尿蛋白趋势图
	public void UriaProtein() throws ServletException,IOException{
		// TODO Auto-generated method stub
		String userid=ServletActionContext.getRequest().getParameter("UserID");
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
        JSONObject returnjson=new JSONObject();	
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(userid);
			if(userid!=null&&!userid.equals("")){
				flag=1;
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("id", id);
				System.out.println(params);
				String sql="select UriaProtein from userhealthdata where UserID =:id ";
				userhealthdatalist=this.userhealthdataservice.findBySql(sql, params);					
				System.out.println(userhealthdatalist);
				returnjson.put("flag", flag);
				returnjson.put("UriaProtein", userhealthdatalist);
			}else{
				flag=0;			
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//查看体重趋势图
	public void Weight() throws ServletException,IOException{
		// TODO Auto-generated method stub
		String userid=ServletActionContext.getRequest().getParameter("UserID");
		userid = java.net.URLDecoder.decode(userid,"UTF-8");
        JSONObject returnjson=new JSONObject();	
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		try {
			PrintWriter out = response.getWriter();
			int id=Integer.parseInt(userid);
			if(userid!=null&&!userid.equals("")){
				flag=1;
				Map<String, Object> params = new HashMap<String, Object>();
			    params.put("id", id);
				System.out.println(params);
				String sql="select Weight from userhealthdata where UserID =:id ";
				userhealthdatalist=this.userhealthdataservice.findBySql(sql, params);					
				System.out.println(userhealthdatalist);
				returnjson.put("flag", flag);
				returnjson.put("Weight", userhealthdatalist);
			}else{
				flag=0;			
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;
	}
	
	public List<Orders> getOrderlist() {
		return orderlist;
	}
	public void setOrderlist(List<Orders> orderlist) {
		this.orderlist = orderlist;
	}
	public Userhealthdata getUserhealthdata() {
		return userhealthdata;
	}
	public void setUserhealthdata(Userhealthdata userhealthdata) {
		this.userhealthdata = userhealthdata;
	}

	public List<Userhealthdata> getUserhealthdatalist() {
		return userhealthdatalist;
	}

	public void setUserhealthdatalist(List<Userhealthdata> userhealthdatalist) {
		this.userhealthdatalist = userhealthdatalist;
	}

	public List<Map<String, Object>> getUserlist() {
		return userlist;
	}

	public void setUserlist(List<Map<String, Object>> userlist) {
		this.userlist = userlist;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

}
